package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.common.util.Constants;
import com.tanhua.common.util.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.tanhua.common.util.Constants.SMS_CODE;

/**
 * @author : xyiaao
 * @createDate : 2022/3/14 11:09
 */
@Service
public class UserService {

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;


    @Autowired
    private HuanXinTemplate huanXinTemplate;


    @Autowired
    private Redisson redisson;


    /**
     * 发送短信验证码
     *
     * @param phone
     */
    public void sendMsg(String phone) {

        // 1、随机生成6位数字
        // String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        // 2、使用setnx将验证码存入到redis，如果已经存在则返回false，存入成功返回true
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(SMS_CODE + phone, code, Duration.ofMinutes(5));
        if (!absent) {
            return;
        }
        // 3、调用template对象，发送手机短信
        // smsTemplate.sendSms(phone, code);
    }

    public Map loginVerification(String phone, String code) {

        // redisson 分布式锁，防止新用户重复注册
        RLock lock = redisson.getLock(phone);
        try {
            lock.lock(60, TimeUnit.SECONDS);
            // 1、从redis中获取下发的验证码
            String redisCode = redisTemplate.opsForValue().get(SMS_CODE + phone);
            // 2、对验证码进行校验(验证码是否存在，是否和输入的验证码一致)
            if (StringUtils.isEmpty(redisCode) || !StringUtils.equals(redisCode, code)) {
                throw new RuntimeException("验证码错误");
            }
            // 3、删除redis中的验证码
            redisTemplate.delete(SMS_CODE + phone);
            // 4、通过手机号码查询用户
            User user = userApi.findByMobile(phone);
            // 区分新老用户，前端使用
            boolean isNew = false;
            // 5、如果用户不存在，创建用户保存到数据库
            if (user == null) {
                user = new User();
                user.setMobile(phone);
                user.setPassword(DigestUtils.md5Hex("123456"));
                Long userId = userApi.save(user);
                user.setId(userId);
                isNew = true;

                // 注册环信用户
                String hxUser = Constants.HX_USER_PREFIX + userId;
                Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
                if (create) {
                    user.setHxUser(hxUser);
                    user.setHxPassword(Constants.INIT_PASSWORD);
                    userApi.update(user);
                }
            }
            // 6、通过JWT生成token
            Map tokenMap = new HashMap();
            tokenMap.put("id", user.getId());
            tokenMap.put("mobile", phone);
            String token = JwtUtils.getToken(tokenMap);
            // 7、构造返回值
            Map retMap = new HashMap();
            retMap.put("token", token);
            retMap.put("isNew", isNew);

            return retMap;
        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

}
